package cn.snowsoft.iot.module.cps.service.product;

import cn.snowsoft.iot.framework.common.pojo.CommonResult;
import cn.snowsoft.iot.module.cps.controller.admin.home.vo.ProductAssociationEquipmentVO;
import cn.snowsoft.iot.module.cps.controller.admin.home.vo.ProductStatusVO;
import cn.snowsoft.iot.module.cps.controller.admin.product.vo.ProductPage;
import cn.snowsoft.iot.module.cps.controller.admin.product.vo.ProductPageVO;
import cn.snowsoft.iot.module.cps.dal.dataobject.product.ProductDO;
import cn.snowsoft.iot.module.cps.dal.mysql.product.ProductMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> implements ProductService {

    @Resource
    private ProductPointService pointService;

    @Override
    public IPage<ProductPage> selectProductPage(ProductPageVO pageVO) {
        IPage<ProductPage> page = new Page<>(pageVO.getPageNo(), pageVO.getPageSize());
        return baseMapper.selectProductPage(page, pageVO);
    }

    @Override
    public CommonResult<Boolean> removeProduct(List<Long> ids) {
        // 判断产品下是否关联设备
        List<ProductPage> pages = this.isAssociationEquipment(ids);
        for (ProductPage page : pages) {
            if (page.getEquipmentCount() > 0) {
                return CommonResult.success(false);
            }
        }
        // 删除相关点位信息
        for (Long id : ids) {
            pointService.removePoint(id);
        }
        removeBatchByIds(ids);
        return CommonResult.success(true);
    }

    @Override
    public List<ProductAssociationEquipmentVO> getEquipmentCount() {
        return baseMapper.getEquipmentCount();
    }

    @Override
    public List<ProductStatusVO> getIsEnableCount() {
        return baseMapper.getIsEnableCount();
    }

    @Override
    public List<ProductDO> getByProductSortId(Long id) {
        return baseMapper.selectList(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getProductSortId, id));
    }

    @Override
    public ProductDO getByCode(String productCode) {
        return baseMapper.selectOne(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getProductCode, productCode));
    }

    public List<ProductPage> isAssociationEquipment(List<Long> ids) {
        return baseMapper.isAssociationEquipment(ids);
    }
}
